// AmbientLight 环境光
import { 
  AmbientLight, 
  AxesHelper, 
  Color, 
  Mesh, 
  MeshLambertMaterial, 
  PerspectiveCamera, 
  PlaneGeometry, 
  Scene, 
  Vector3, 
  WebGLRenderer 
} from "three"
import { TrackballControls } from 'three/examples/jsm/controls/TrackballControls'
import stats from '../utils/stats';
import { GUI } from 'dat.gui'

const scene = new Scene()
const camera = new PerspectiveCamera(45, window.innerWidth/window.innerHeight, 0.1, 1000)
const renderer = new WebGLRenderer({ antialias: true });
renderer.setClearColor(0x000000);
renderer.setPixelRatio(window.devicePixelRatio);
renderer.setSize(window.innerWidth, window.innerHeight);
renderer.shadowMap.enabled = true;

document.body.appendChild(renderer.domElement);

// 创建一个平面
const planeGeometry = new PlaneGeometry(60, 40, 1, 1)
const planeMaterial = new MeshLambertMaterial({ color: 0xffffff })
const plane = new Mesh(planeGeometry, planeMaterial)
// 接收阴影
plane.receiveShadow = true

plane.rotation.x = -0.5 * Math.PI
plane.position.set(0, 0, 0)
scene.add(plane)

// 添加坐标系，方便理解
const axes = new AxesHelper(15)
scene.add(axes)

// 设置相机位置
camera.position.set(-30, 40, 30)
camera.lookAt(new Vector3(5, 0, 0))

// 添加环境光
let ambientColor = 0xeeeeee;
const ambientLight = new AmbientLight(ambientColor)
scene.add(ambientLight)

// 控制器
let controls = {
  ambientColor
}
const gui = new GUI();
// 颜色选择功能
gui.addColor(controls, 'ambientColor')
  .onChange(e => {
    ambientLight.color = new Color(e)
  })

// 引入轨迹球控制器，添加鼠标控制功能
const trackballControls = new TrackballControls(camera, renderer.domElement)

function render() {
  trackballControls.update();
  stats.update();

  requestAnimationFrame(render)
  renderer.render(scene, camera)
}
render()